package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author liuchun
 * @since 2024-08-30
 */
@Service
@SuppressWarnings("all")
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {


    @Autowired
    private UserClient userClient;

    @Autowired
    private InteractionQuestionMapper questionMapper;
    /**
     * 新增回答或评论
     * @param replyDTO
     */
    @Override
    public void addReply(ReplyDTO replyDTO) {
        //获取用户id
        Long userId = UserContext.getUser();
        InteractionReply reply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        //设置属性
        reply.setUserId(userId);
        //保存
        save(reply);
        //判断是否是回答，dto.answerId 为空则是回答
        InteractionQuestion question = questionMapper.selectById(replyDTO.getQuestionId());;
        if (replyDTO.getAnswerId() != null) {
            //不是回答
            InteractionReply answerInfo = getById(replyDTO.getAnswerId());
            answerInfo.setReplyTimes(answerInfo.getReplyTimes() + 1);
            updateById(answerInfo);
        }else {
            //是回答
            question.setLatestAnswerId(reply.getId());
            question.setAnswerTimes(question.getAnswerTimes() + 1);
        }
        if (replyDTO.getIsStudent()){
            question.setStatus(QuestionStatus.UN_CHECK);
        }
        questionMapper.updateById(question);
    }

    /**
     * 分页查询回答或评论列表
     * @param pageQuery
     * @return
     */
    @Override
    public PageDTO<ReplyVO> pageReply(ReplyPageQuery pageQuery) {
        //校验questionId和anserId是否都为空
        if(pageQuery.getQuestionId() == null && pageQuery.getAnswerId() == null){
            throw new BadRequestException("问题和回答Id不能都为空");
        }
        Page<InteractionReply> page = lambdaQuery()
                .eq(pageQuery.getQuestionId() != null, InteractionReply::getQuestionId, pageQuery.getQuestionId())
                .eq(pageQuery.getAnswerId() != null, InteractionReply::getAnswerId, pageQuery.getAnswerId())
                .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionReply> records = page.getRecords();
        //为空
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //调用用户服务
        Set<Long> userIds = records.stream().map(InteractionReply::getUserId).collect(Collectors.toSet());
        Set<Long> tIds = records.stream().map(InteractionReply::getTargetUserId).collect(Collectors.toSet());

        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userMap = new HashMap<>(userIds.size());
        if (CollUtils.isNotEmpty(userDTOS)) {
            userMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, c -> c));
        }
        List<UserDTO> tUserDTOS = userClient.queryUserByIds(tIds);
        Map<Long, UserDTO> tUserMap = new HashMap<>(tIds.size());
        if (CollUtils.isNotEmpty(tUserDTOS)){
            tUserMap = tUserDTOS.stream().collect(Collectors.toMap(UserDTO::getId, c -> c));
        }
        List<ReplyVO> vos = new ArrayList<>(records.size());
        for (InteractionReply record : records) {
            ReplyVO vo = BeanUtils.copyBean(record, ReplyVO.class);
            vo.setUserName(userMap.get(record.getUserId()).getUsername());
            vo.setUserIcon(userMap.get(record.getUserId()).getIcon());
            vo.setTargetUserName(tUserMap.get(record.getTargetUserId()).getUsername());
            vos.add(vo);
        }
        return PageDTO.of(page,vos);
    }
}
